package com.kwshare.monitor.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

/**
 * 监控权限配置
 *
 * @author yangjing
 */
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter
{
    /** 默认目标路径 */
    private final String adminContextPath;

    /**
     * 设置默认目标路径
     *
     * @param adminServerProperties adminServerProperties
     */
    public WebSecurityConfigurer(AdminServerProperties adminServerProperties)
    {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    /**
     * 监控权限配置
     *
     * @param http http
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        // 构建SavedRequestAwareAuthenticationSuccessHandler对象
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        // 重定向到登录页
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");

        http
                .headers().frameOptions().disable()
                .and().authorizeRequests()
                // 放行对应接口
                .antMatchers(adminContextPath + "/assets/**"
                        , adminContextPath + "/login"
                        , adminContextPath + "/actuator/**"
                        , adminContextPath + "/instances/**"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
                // 设置登录路径
                .formLogin().loginPage(adminContextPath + "/login")
                .successHandler(successHandler).and()
                // 设置登出路径
                .logout().logoutUrl(adminContextPath + "/logout")
                .and()
                .httpBasic().and()
                .csrf()
                .disable();
    }
}
